package com.enjoy.concurrent.ch2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "enjoy")
public class SemaphoreTest {
    private static final Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) throws InterruptedException {


        new Thread(() -> {
            try {
                semaphore.acquire();
                log.info("执行了");
                TimeUnit.HOURS.sleep(100);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                semaphore.release();
            }
        }, "t1").start();

        Thread.sleep(1000);

        new Thread(() -> {
            try {
                semaphore.acquire();
                log.info("执行了");
                TimeUnit.HOURS.sleep(100);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                semaphore.release();
            }
        }, "t2").start();

        Thread.sleep(1000);

        new Thread(() -> {
            try {
                semaphore.acquire();
                log.info("执行了");
                TimeUnit.HOURS.sleep(100);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            } finally {
                semaphore.release();
            }
        }, "t3").start();


    }
}
